<template>
  <div class="content-header">
    <el-row>
      <el-card class="box-card wisdom-card-header">
        <el-page-header
          @back="backHome"
          icon="el-icon-arrow-left"
          :content="cardName"
          title="返回主页"
        />
        <div class="wisdom-card-header-action">
          <div style="margin-top: 1rem"></div>
          <div>
            <p>找不到需要的资源？在这里发布你想要的资源吧</p>
          </div>
          <div style="margin-top: 1rem"></div>
          <div>
            <el-button
              type="primary"
              size="medium"
              @click="dialogTableVisible = true"
              >发布求助</el-button
            >
          </div>
        </div>
      </el-card>
    </el-row>

    <el-row align="top" v-show="false">
      <el-card class="card-control">
        <el-row :gutter="20">
          <el-col :span="3">
            <div class="card-lable">
              <TopRight
                style="
                  width: 1em;
                  height: 1em;
                  margin-right: 5px;
                  margin-top: 4px;
                "
              />
              <span>排序类型</span>
            </div>
          </el-col>
          <el-col :span="18">
            <div class="card-lable-content">
              <!-- 按照data里的配置生成按钮组 -->
              <el-button-group size="small">
                <el-button
                  v-for="(btn, index) in buttonGroup"
                  :key="index"
                  :class="activeClass == index ? 'el-button--primary' : ''"
                  @click="changeChecked(btn.index)"
                  >{{ btn.name }}</el-button
                >
              </el-button-group>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="3">
            <div class="card-lable">
              <span>
                <search
                  style="
                    width: 1em;
                    height: 1em;
                    margin-right: 5px;
                    margin-top: 4px;
                  "
                />
              </span>
              <span>条件筛选</span>
            </div>
          </el-col>
          <el-col :span="18">
            <div class="card-lable-content" style="margin-bottom: 0">
              <el-input
                style="width: 260px"
                v-model="search_wisdom"
                placeholder="搜索用户名/标签类型"
                clearable
              />
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-row>

    <el-row style="overflow: auto">
      <el-scrollbar style="width: 100%">
        <el-row
          v-loading="list_loading_wisdom"
          element-loading-text="拼命加载资源中"
          element-loading-background="rgba(255, 255, 255, 1)"
          style="margin: 10px 0 10px 0"
        >
          <div
            style="
              min-height: 9.375rem;
              background-color: #ffffff;
              margin: 10px 0 10px 0;
            "
            v-show="list_loading_wisdom"
          ></div>
          <el-col
            :xs="{ span: 24 }"
            :sm="{ span: 24 }"
            :md="{ span: 12 }"
            :lg="{ span: 8 }"
            :xl="{ span: 8 }"
            v-for="(wisdomItem, index) in wisdomList"
            :key="index"
          >
            <el-card
              class="wisdom-card-child card-list-item"
              shadow="hover"
              :body-style="{ padding: '20px' }"
            >
              <template #header>
                <img
                  width="64"
                  height="64"
                  :src="wisdomItem.userInfo.portrait"
                  class="image_avatar"
                />
                <div>
                  <span class="card_title" style="font-size: 18px"
                    >{{ wisdomItem.userId }}的求助💡</span
                  >
                  <div class="bottom">
                    <div class="card_content">
                      {{ wisdomItem.wish_content }}
                    </div>
                    <!-- 标签模块 -->
                    <div>
                      <span
                        v-for="(tag, index) in wisdomItem.wish_tag_list"
                        :key="index"
                      >
                        <el-tag
                          class="tag-style tag-speciall-style"
                          type="info"
                        >
                          {{ tag }}
                        </el-tag>
                      </span>
                    </div>
                  </div>
                </div>
              </template>
              <div class="card_content_bottom">
                <div class="card_content_time">
                  发布时间：{{ wisdomItem.wish_time }}
                </div>
                <div class="card_content_status">
                  <el-tag type="success">已完成</el-tag>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <!-- 底部分页模块 -->
        <el-row>
          <el-card shadow="never" class="card-page">
            <el-pagination
              ref="wisdomPage"
              background
              layout="prev, pager, next, total"
              :total="listNum"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="pageChange"
            >
            </el-pagination>
          </el-card>
        </el-row>
      </el-scrollbar>
    </el-row>

    <el-dialog v-model="dialogTableVisible" title="发布互助信息">
      <el-form
        class="wisdomForm"
        ref="wisdomForm"
        label-width="100px"
        label-position="right"
        :model="addWisdomData"
        :rules="rules"
      >
        <el-form-item style="width: 100%" label="互助描述" prop="wish_content">
          <el-input
            v-model="addWisdomData.wish_content"
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"
            placeholder="填写你需要的资源描述,尽量分类明确有指向性"
            clearable
          >
          </el-input>
        </el-form-item>

        <el-form-item style="width: 100%" label="互助分类">
          <el-select
            style="width: 100%"
            v-model="addWisdomData.wish_tag"
            placeholder="选择互助分类标签"
            multiple
            clearable
            filterable
            :multiple-limit="3"
          >
            <el-option-group
              v-for="group in allTags"
              :key="group.lable"
              :label="group.lable"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="addWisdom()"
            :loading="wisdomLoading"
            >提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import tags from "@/resource/tags.json";
import Qs from "qs";
import { ElMessage } from "element-plus";
export default {
  created() {
    this.getWisdomList();
  },
  data() {
    return {
      //-1代表都不选择，改变量对应buttonGroup选中的按钮index
      activeClass: 0,
      listNum: 0,
      currentPage: 1,
      pageSize: 6,
      dialogTableVisible: false,
      list_loading_wisdom: true,
      search_wisdom: "",
      cardName: this.$route.meta.title,
      wisdomLoading: false,
      allTags: tags,
      wisdomList: [],
      addWisdomData: {
        userId: localStorage.pg_username,
        wish_content: "",
        wish_tag: [],
      },
      rules: {
        wish_content: [
          {
            required: true,
            message: "请输入互助描述",
            trigger: "blur",
          },
          {
            max: 80,
            message: "字数不能超过200个",
            trigger: "blur",
          },
        ],
        tags: [
          {
            required: true,
            message: "请选择求助分类",
            trigger: ["blur", "change"],
          },
        ],
      },
      buttonGroup: [
        {
          index: 0,
          name: "默认",
        },
        {
          index: 1,
          name: "时间",
        },
        {
          index: 2,
          name: "评价",
        },
        {
          index: 3,
          name: "点击",
        },
      ],
    };
  },
  methods: {
    changePageTotalStyle() {
      this.$nextTick(() => {
        this.$refs.wisdomPage.$el.children[3].innerHTML =
          "总共" + " " + this.listNum + " " + "条记录";
        this.$refs.wisdomPage.$el.children[3].style.margin = "0 10px 0 10px";
      });
    },
    checkIsJsonString(str: string) {
      try {
        //通过JSON将str转换为json对象，如果转换出现异常，进入catch,返回false
        let obj = JSON.parse(str);
        if (typeof obj === "object" && obj) {
          return true;
        } else {
          return false;
        }
      } catch (error) {
        //转换异常，返回false
        return false;
      }
    },
    pageChange(currentPage: number) {
      this.currentPage = currentPage;
      this.wisdomList = [];
      this.list_loading_wisdom = true;
      setTimeout(() => {
        this.getWisdomList(currentPage, 6);
      }, 200);
    },
    getWisdomList(r_pageNum = 1, r_pageSize = 6) {
      let that = this;
      //发送请求
      this.$axios({
        url: "http://localhost:8080/wisdom/listWisdom",
        method: "post",
        headers: {
          token: localStorage.pg_token,
        },
        transformRequest: [
          function (data: any) {
            // 对 data 进行任意转换处理
            return Qs.stringify(data);
          },
        ],
        data: {
          pageNum: r_pageNum,
          pageSize: r_pageSize,
        },
        transformResponse: [
          function (data: string) {
            // 对接收的 data 进行任意转换处理
            let result;
            if (that.checkIsJsonString(data)) {
              result = JSON.parse(data);
            } else {
              ElMessage({
                message: "请求服务器返回数据失败",
                type: "error",
              });
              that.list_loading_wisdom = false;
              return data;
            }

            // console.log(result);
            if (result.code === 200) {
              that.wisdomList = result.data.resultList;
              that.listNum = result.data.listCount;
              // that.$router.go(0);
            } else {
              ElMessage({
                message: result.msg + "(" + result.error_code + ")",
                type: "error",
              });
              // that.$router.go(0);
            }
            that.list_loading_wisdom = false;
            return data;
          },
        ],
      })
        .catch((error: any) => {
          ElMessage({
            message: "请求服务器出现异常",
            type: "error",
          });
          this.changePageTotalStyle();
        })
        .then(() => {
          this.changePageTotalStyle();
        });
    },
    addWisdom() {
      let that = this;
      this.wisdomLoading = true;
      this.$refs.wisdomForm.validate((valid: any) => {
        if (valid) {
          this.wisdomLoading = false;
          //发送请求
          this.$axios({
            url: "http://localhost:8080/wisdom/savaWisdom",
            method: "post",
            transformRequest: [
              function (data: any) {
                // 对 data 进行任意转换处理
                console.log(JSON.stringify(data));
                return JSON.stringify(data);
              },
            ],
            headers: {
              "Content-Type": "application/json",
              token: localStorage.pg_token,
            },
            data: this.addWisdomData,
            transformResponse: [
              function (data: string) {
                // 对接收的 data 进行任意转换处理
                let result;
                if (that.checkIsJsonString(data)) {
                  result = JSON.parse(data);
                } else {
                  ElMessage({
                    message: "请求服务器返回数据失败",
                    type: "error",
                  });
                  that.list_loading_wisdom = false;
                  return data;
                }

                // console.log(result);
                if (result.code === 200) {
                  ElMessage({
                    message: "求助信息提交成功，审核通过后系统自动为您发布",
                    type: "success",
                  });
                  // that.$router.go(0);
                } else {
                  ElMessage({
                    message: result.msg,
                    type: "error",
                  });
                  // that.$router.go(0);
                }
                that.$router.go(0);
                return data;
              },
            ],
          });
        } else {
          // setTimeout(() => {
          // 	let isError = document.getElementsByClassName("is-error");
          // 	isError[0].focus();
          // }, 100);
          return false;
        }
      });
    },
    changeChecked(index: number) {
      this.activeClass = index; // 把当前点击元素的index，赋值给activeClass
      // console.log(this.$route.meta.title);
    },
    backHome() {
      // console.log('back');
      this.$router.push("/Home");
    },
  },
};
</script>

<style scoped>
html {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}

.tag-style {
  margin: 0 0.3125rem 0.3125rem 0;
  border-radius: 0.3125rem;
}

.wisdomForm {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  text-align: left;
}

.image_avatar {
  border-radius: 50%;
}

.card-page {
  width: -webkit-fill-available;
  cursor: default !important;
  margin: 0 0.5rem 0 0.5rem;
  border-radius: 0.3125rem;
}

.container {
  position: relative;
  display: flex;
  flex-flow: row wrap;
  overflow: auto;
}

.wisdom-card-child:hover .card_title {
  color: #c85554;
  font-weight: 500;
  transition: 0.1s;
}

.wisdom-card-child {
  margin: 10px;
  cursor: pointer;
}

.card-list {
  margin-top: 0px !important;
  height: 100%;
  box-sizing: border-box;
  cursor: default !important;
  text-align: left;
}

.card_content {
  /* padding: 10px; */
  margin: 10px 0 10px 0;
  color: #999999;
  font-size: 14px;
  text-align: center;
  min-height: 40px;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card_content_bottom {
  display: flex;
  justify-content: space-between;
}

.card_content_time {
  /* padding: 10px; */
  color: #999999;
  font-size: 13px;
  text-align: left;
}

.card_content_status {
  font-size: 13px;
}

.content-header {
  display: flex;
  flex-grow: 1;
  margin: 0 5px 0 5px;
  flex-direction: column;
  /* flex-wrap: wrap; */
  /* background-color: #FFF; */
}

.el-button:active {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #ecf5ff;
}

.card-lable {
  display: flex;
  align-items: stretch;
  text-align: center;
  height: 100%;
}

.card-lable-content {
  display: flex;
  align-items: auto;
  text-align: left;
  margin-bottom: 1.25rem;
  /* height: 100%; */
}

.card-control {
  margin: 0.3125rem 0 0.3125rem 0;
  width: -webkit-fill-available;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wisdom-card-header {
  height: 145px;
  width: 100%;
  margin: 0;
}

.wisdom-card-header-action {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: column;
  /* margin-top: 1.5rem; */
}

/* .el-page-header__left{
		width: 0;
		display: none;
	} */
</style>
